package com.grf.kafka.java.serializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @apiNote 用户对象序列化
 * @author grf
 * @since 2024/10/25
 */
@Slf4j
public class UserSerializer implements Serializer<User> {
    @Override
    public byte[] serialize(String s, User user) {
        byte[] nameBytes = user.getName().getBytes(StandardCharsets.UTF_8);
        // id:long-8;name: int-4,string-length;age:int-4;sex:int-4
        int cap = 8+4+4+4+nameBytes.length;
        ByteBuffer byteBuffer = ByteBuffer.allocate(cap);
        byteBuffer.putLong(user.getId());
        byteBuffer.putInt(user.getAge());
        byteBuffer.putInt(user.getSex());
        byteBuffer.putInt(nameBytes.length);
        byteBuffer.put(nameBytes);

        return byteBuffer.array();
    }
}
